<template>
  <div class="batch-flow-container">
    <!-- 搜索条件区域 -->
    <div class="search-section">
      <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
        <!-- 第一行搜索条件 -->
        <div class="search-row">
          <el-form-item label="出入库单号" prop="inOutNo">
            <el-input 
              v-model="searchForm.inOutNo" 
              placeholder="请输入出入库单号"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          
          <el-form-item label="出入库日期" prop="inOutTiem">
            <el-date-picker
              v-model="searchForm.inOutTiem"
              type="date"
              placeholder="请选择"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 150px"
            />
          </el-form-item>
          
          <el-form-item label="业务类型" prop="businessType">
            <el-select 
              v-model="searchForm.businessType" 
              placeholder="请选择"
              clearable
              style="width: 120px"
            >
              <el-option label="入库" value="入库" />
              <el-option label="出库" value="出库" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="单据时间" prop="createTime">
            <el-date-picker
              v-model="searchForm.createTime"
              type="date"
              placeholder="请选择"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 150px"
            />
          </el-form-item>
        </div>
        
        <!-- 第二行搜索条件 -->
        <div class="search-row">
          <el-form-item label="仓库名称" prop="inventory">
            <el-select 
              v-model="searchForm.inventory" 
              placeholder="请选择"
              clearable
              style="width: 150px"
            >
              <el-option label="仓库一" value="仓库一" />
              <el-option label="仓库二" value="仓库二" />
              <el-option label="仓库三" value="仓库三" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="出库数量" prop="outNumberRange">
            <el-input 
              v-model="searchForm.outNumberMin" 
              placeholder="请输入"
              style="width: 80px"
            />
            <span style="margin: 0 8px">~</span>
            <el-input 
              v-model="searchForm.outNumberMax" 
              placeholder="请输入"
              style="width: 80px"
            />
          </el-form-item>
          
          <el-form-item label="入库数量" prop="inNumberRange">
            <el-input 
              v-model="searchForm.inNumberMin" 
              placeholder="请输入"
              style="width: 80px"
            />
            <span style="margin: 0 8px">~</span>
            <el-input 
              v-model="searchForm.inNumberMax" 
              placeholder="请输入"
              style="width: 80px"
            />
          </el-form-item>
        </div>
        
        <!-- 操作按钮 -->
        <div class="button-row">
          <el-button @click="handleExport" type="default">导出</el-button>
          <el-button @click="handleRefresh" type="default">刷新</el-button>
          <el-button @click="handleReset" type="default">重置</el-button>
          <el-button @click="handleSearch" type="primary">查询</el-button>
        </div>
      </el-form>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-section">
      <el-table 
        :data="tableData" 
        v-loading="loading"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="index" label="序号" width="120" />
        <el-table-column prop="inOutNo" label="出入库单号" width="200" />
        <el-table-column prop="inOutTiem" label="出入库日期" width="180" />
        <el-table-column prop="inventory" label="仓库名称" width="180" />
        <el-table-column prop="businessType" label="业务类型" width="150">
          <template #default="scope">
            <el-tag 
           
              size="small"
            >
              {{ scope.row.businessType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="outNumbber" label="出库数量" width="100">
          <template #default="scope">
            {{ scope.row.outNumbber === 0 ? '' : scope.row.outNumbber }}
          </template>
        </el-table-column>
        <el-table-column prop="inNumber" label="入库数量" width="100">
          <template #default="scope">
            {{ scope.row.inNumber === 0 ? '' : scope.row.inNumber }}
          </template>
        </el-table-column>
        <el-table-column prop="createer" label="制单人" width="100" />
        <el-table-column prop="createTime" label="单据时间" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import moment from 'moment'
import { TZRead } from '@/http/interceptors'

const route = useRoute()
const router = useRouter()

// 搜索表单数据
const searchForm = reactive<{
  inOutNo: string
  inOutTiem: string
  businessType: string
  createTime: string
  inventory: string
  outNumberMin: string
  outNumberMax: string
  inNumberMin: string
  inNumberMax: string
  batchId: string
}>({
  inOutNo: '',
  inOutTiem: '',
  businessType: '',
  createTime: '',
  inventory: '',
  outNumberMin: '',
  outNumberMax: '',
  inNumberMin: '',
  inNumberMax: '',
  batchId: '' // 从路由参数获取的批次ID
})

// 分页数据
const pagination = reactive<{
  pageIndex: number
  pageSize: number
  total: number
}>({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref<any[]>([])
const loading = ref(false)

// 表单引用
const searchFormRef = ref<any>()

// 日期时间格式化函数
const formatDateTime = (date: any) => {
  if (!date) return ''
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

// 查询数据
const loadData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params: any = {
      Pageindex: pagination.pageIndex,
      Pagesize: pagination.pageSize,
      Batch_Id: searchForm.batchId || undefined,
      InOutNo: searchForm.inOutNo || undefined,
      InOutTiem: searchForm.inOutTiem || undefined,
      BusinessType: searchForm.businessType || undefined,
      CreateTime: searchForm.createTime || undefined,
      Inventory: searchForm.inventory || undefined,
      InNumber: searchForm.inNumberMin ? parseInt(searchForm.inNumberMin) : undefined,
      OutNumbber: searchForm.outNumberMin ? parseInt(searchForm.outNumberMin) : undefined
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete (params as any)[key]
      }
    })

    // 调用批次流水查询API接口
    const res = await TZRead.get("/api/Product/batchflow-list", { params })
    
    if (res.data.code === 200) {
      // 处理数据：添加序号
      const processedData = (res.data.pageData as any[]).map((item: any, index: number) => {
        return {
          ...item,
          index: (pagination.pageIndex - 1) * pagination.pageSize + index + 1
        }
      })
      
      tableData.value = processedData
      pagination.total = res.data.totalCount
      
      ElMessage.success('查询成功')
    } else {
      ElMessage.error(res.data.message || '查询失败')
    }
  } catch (error: any) {
    ElMessage.error('查询失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleSearch = () => {
  pagination.pageIndex = 1
  loadData()
}

// 重置按钮
const handleReset = () => {
  searchFormRef.value?.resetFields()
  // 保留批次ID，不清空
  const batchId = searchForm.batchId
  Object.keys(searchForm).forEach(key => {
    if (key !== 'batchId') {
      (searchForm as any)[key] = ''
    }
  })
  searchForm.batchId = batchId
  pagination.pageIndex = 1
  loadData()
}

// 刷新按钮
const handleRefresh = () => {
  loadData()
}

// 导出按钮
const handleExport = () => {
  ElMessage.info('导出功能待实现')
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  loadData()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  loadData()
}

// 页面初始化
onMounted(() => {
  // 从路由参数获取批次ID
  if (route.query.Batch_Id) {
    searchForm.batchId = route.query.Batch_Id as string
  }
  
  // 加载数据
  loadData()
})
</script>

<style scoped>
.batch-flow-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  width: 100%;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

.button-row {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  padding: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-table) {
  border-radius: 8px 8px 0 0;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}
</style>